import router from './router';
import Layout from '@/layout/index.vue';
import { ElMessage } from 'element-plus';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken, setToken } from '@/utils/auth';
NProgress.configure({ showSpinner: false });
import { useUserStore } from "@/stores/user";
const useStore = useUserStore();
const whiteList = ['/login'];
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getToken()) {
    console.log('已登录')
    //在这里处理有token的逻辑
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      if (useStore.roles.length === 0) {
        useStore.getUserInfoFun()
          .then(() => {
            useStore
              .generateRoutes()
              .then((accessRoutes) => {
                const menus = loadMenu(accessRoutes)//过滤路由
                useStore.menus = menus;
                menus.forEach((item) => {
                  router.addRoute(item);
                });
                next({ path: to.path });

              });
          })
          .catch((err) => {
            useStore
              .logOut()
              .then(() => {
                next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
              });
          });
        //这里只要用户刷新页面就会调用，跳转页面则不会调用 (刷新页面store会清空)   
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});





const modules = import.meta.glob("@/views/**/**.vue") //引入views下的所有文件，返回一个对象
export function loadMenu(menuList) {
  let routeList = [];
  menuList.forEach((m) => {
    let oneMenu = m.children[0];
    let data;
    let moreMenu = m;
    if (m.hasOwnProperty('children') && m.children != null && m.children.length === 1) {
      data = {
        path: oneMenu.path,
      //  component:Layout,//公共布局
        component: modules['/src/views/' + oneMenu.component + '.vue'],
        name: oneMenu.name,
        meta: {
          title: oneMenu.meta.title,
        },
        children: [],
        hidden: oneMenu.meta.noCache,
      }
    } else {
      data = {
        path: moreMenu.path,
        component: Layout,
        name: moreMenu.name,
        meta: {
          title: moreMenu.meta.title,
        },
        children: [],
        hidden: moreMenu.meta.noCache,
      }

    }

    if (m.hasOwnProperty('children') && m.children != null && m.children.length > 1) {
      m.children.forEach((c) => {
        let componentName = c.component;
        var childrenData = {
          path: c.path,
          name: c.path.substring(1),
          component: modules['/src/views/' + componentName + '.vue'],
          hidden: c.hidden,
          meta: {
            title: c.meta.title,
            icon: c.meta.icon,
            keepAlive: c.meta.noCache,//是否缓存,1不缓存 0缓存
          }
        }
        data.children.push(childrenData);
      })
    }
    routeList.push(data);
  })

  return routeList;
}

